--- redirect_from: - "/03/subsection/02-04-05/sos-notebook5" interact_link: content/03/subsection/02-04-05/sos_notebook5.ipynb kernel_name: sos kernel_path: content/03/subsection/02-04-05 has_widgets: false title: |- Fig 5. Results of knockout analysis pagenum: 8 prev_page: url: /03/subsection/02-04-05/sos_notebook4.html next_page: url: /03/subsection/06/sos_notebook6.html suffix: .ipynb search: cm neuron python figures plotly f influential github sos interactive author calculations written com figure firing rate e least neurons mean error code example jupyter notebook script scripts vatlab io docs workflow reproduces paper ardi tampuu last raul vicente using fetched repo neurocsut ratgps ploting library maps according knockout analysis colour bar right plot indicates hz complete dataset knocking five increased respectively doi org journal pcbi g b c d comment: "***PROGRAMMATICALLY GENERATED, DO NOT EDIT. SEE ORIGINAL FILES IN /content***" ---
Fig 5. Results of knockout analysis

This code example is a Jupyter notebook with Script of Scripts (SoS) workflow. It reproduces interactive figures for the paper by first author Ardi Tampuu and last author Raul Vicente.

The calculations are written using Python 2.7 (from this fetched from repo), and the interactive figures are written in Python 3.6 with the ploting library Plotly.

Figure 5:

The firing rate maps of the most (a-e) and least (f) influential neurons according to the knockout analysis. Colour bar to the right of each plot indicates the firing rate in Hz. With the complete dataset the mean error was 12.50±0.28 cm. When knocking out neurons 55, 26, 41, 17, 23 (the five most influential) and 9 (the least influential), the mean error increased to 14.72 cm, 13.80 cm, 13.66 cm, 13.50 cm, 13.49 cm and 12.58 cm respectively.

https://doi.org/10.1371/journal.pcbi.1006822.g005

Python 2.7


Figure 5 a-f:

%use Python2
from ratdata import load_data
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.style
import matplotlib as mpl
# mpl.style.use('classic')


data = np.load('R2192_models/grads_R2192_1x1400_v1.npz')
#grads = data['grads'][:,:,:63]
grads = data['grads'][:,:,:63]
#onehot_grads = data['grads'][:,:,63:]
targets = data['targets']

new_tgts=0
all_grads=[]

# For the article, this was actually done for 10 CV-runs, 
# but to limit repo size we have included only one set of grad to the repository

for i in range(1,2):
    data = np.load("R2192_models/grads_R2192_1x1400_v"+str(i)+".npz")
    grads = data['grads'][:,:,:63]
    if i>1:
        assert(np.all(new_tgts==data["targets"]))
    new_tgts = data["targets"]
    all_grads.append(grads)

mean_grads = np.mean(np.abs(all_grads), axis=0)

neuron_grads = np.mean(mean_grads, axis=(0,1))


feature_importance = neuron_grads

sorted_idx = np.argsort(feature_importance)

X, y = load_data('data/R2192_1x1400_at35_step200_bin100-RAW_feat.dat', 'data/R2192_1x1400_at35_step200_bin100-RAW_pos.dat')

list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'} 

# activity of the most important neurons in 2D space (place fields)
plt.figure(figsize=(24,28))
for i in xrange(1,7):
    plt.subplot(3,2,i)
    plt.hexbin(y[...,0], y[...,1], X[...,sorted_idx[-list_neurons[str(i)]]], gridsize = 15, cmap='jet')
    plt.xlabel("X-coordinate (cm)",fontsize=16)
    plt.ylabel("Y-coordinate (cm)",fontsize=16)
    plt.xticks(fontsize=15)
    plt.yticks(fontsize=15)
    plt.colorbar()
    plt.title(labels_titles[str(i)] + "\n Neuron #%d" % sorted_idx[-list_neurons[str(i)]])
Original data: (5404, 63) (5404, 2)
minX/maxX/meanX/stdX/miny/maxy: 0.0 59.0 0.7402482581979251 2.3591926816354136 4.39033 107.044
%use Python2
import pickle 
with open('train.pickle', 'wb') as f:
    pickle.dump([X, y, sorted_idx], f)

Python 3.7


Figures with calculations in Python 3.7, Plotly:

(a) Neuron #55

%use Python3
from hexplot import  get_hexbin_attributes, pl_cell_color, make_hexagon, mpl_to_plotly
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# import cmocean#  http://matplotlib.org/cmocean/
import pickle
import plotly.graph_objs as go

with open('train.pickle', 'rb') as f:
    X, y,sorted_idx = pickle.load(f, encoding='bytes')

    
list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'}     
    
x = y[...,0]
y = y[...,1]

plt.figure(figsize=(0.05,0.05))
plt.axis('off')
HB = plt.hexbin(x, y, X[...,sorted_idx[-list_neurons["1"]]], gridsize = 15, cmap='jet') # cmocean.cm.algae is a cmocean colormap
%use Python3
import plotly.graph_objects as go
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
from IPython.core.display import display, HTML
init_notebook_mode(connected = True)
config={'showLink': False, 'displayModeBar': False}

# Calculations for fig5.a
hexagon_vertices, offsets, mpl_facecolors, counts = get_hexbin_attributes(HB)
hexagon_vertices[:-1]# the last vertex coincides with the first one
cell_color = pl_cell_color(mpl_facecolors)
shapes = []
centers = []

for k in range(len(offsets)):
    shape, center = make_hexagon(hexagon_vertices, offsets[k], cell_color[k])
    shapes.append(shape)
    centers.append(center)
    

pl_algae = mpl_to_plotly(HB.cmap,11)
X, Y = zip(*centers)

#define  text to be  displayed on hovering the mouse over the cells
text = [f'x: {round(X[k],2)}<br>y: {round(Y[k],2)}<br>Counts: {int(counts[k])}' for k in range(len(X))]

trace = go.Scatter(
             x=list(X), 
             y=list(Y), 
             mode='markers',
             marker=dict(size=0.5, 
                         color=counts, 
                         colorscale=pl_algae, 
                         showscale=True,
                         colorbar=dict(
                                     thickness=20,  
                                     ticklen=4
                                     )),             
           text=text, 
           hoverinfo='text'
          )    

axis = dict(showgrid=False,
           showline=True,
           zeroline=False,
           ticklen=4 
           )
layout = go.Layout(title='Hexbin plot',
                   width=530, height=550,
                   xaxis=axis,
                   yaxis=axis,
                   hovermode='closest',
                   shapes=shapes,
                   plot_bgcolor='black')

figa = go.FigureWidget(data=[trace], layout = layout)

figa.update_layout(title = labels_titles["1"] + "\n Neuron #%d" % sorted_idx[-list_neurons["1"]],
                  title_x = 0.5, 
                  xaxis_title='X-coordinate (cm)',
                  xaxis=dict(mirror=True,
                             ticks='outside',
                             showline=True,
                             linecolor='#000',
                             tickvals = [0,20,40,60,80,100], 
                             tickfont = dict(size=20)), 
                  yaxis_title='Y-coordinate (cm)',
                  yaxis=dict(mirror=True,
                             ticks='outside', 
                             showline=True,
                             linecolor='#000',
                             tickfont = dict(size=20)),
                  plot_bgcolor='#fff', 
                  width = 620, 
                  height = 600,
                  shapes=shapes,
                  hovermode='closest',
                  margin=go.layout.Margin(l=50,
                                          r=50),
                  font = dict(size = 17))

plot(figa, filename = 'fig5_a.html', config = config)
# THEBELAB
display(HTML('fig5_a.html'))
# BINDER
# iplot(figa,config=config)    

(b) Neuron #26

%use Python3
from hexplot import  get_hexbin_attributes, pl_cell_color, make_hexagon, mpl_to_plotly
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# import cmocean#  http://matplotlib.org/cmocean/
import pickle
import plotly.graph_objs as go

with open('train.pickle', 'rb') as f:
    X, y,sorted_idx = pickle.load(f, encoding='bytes')

    
list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'}     
    
x = y[...,0]
y = y[...,1]

plt.figure(figsize=(0.05,0.05))
plt.axis('off')
HB = plt.hexbin(x, y, X[...,sorted_idx[-list_neurons["2"]]], gridsize = 15, cmap='jet') # cmocean.cm.algae is a cmocean colormap
%use Python3
import plotly.graph_objects as go
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
from IPython.core.display import display, HTML
init_notebook_mode(connected = True)
config={'showLink': False, 'displayModeBar': False}

# Calculations for fig5.b
hexagon_vertices, offsets, mpl_facecolors, counts = get_hexbin_attributes(HB)
hexagon_vertices[:-1]# the last vertex coincides with the first one
cell_color = pl_cell_color(mpl_facecolors)
shapes = []
centers = []

for k in range(len(offsets)):
    shape, center = make_hexagon(hexagon_vertices, offsets[k], cell_color[k])
    shapes.append(shape)
    centers.append(center)
    

pl_algae = mpl_to_plotly(HB.cmap,11)
X, Y = zip(*centers)

#define  text to be  displayed on hovering the mouse over the cells
text = [f'x: {round(X[k],2)}<br>y: {round(Y[k],2)}<br>Counts: {int(counts[k])}' for k in range(len(X))]

trace = go.Scatter(
             x=list(X), 
             y=list(Y), 
             mode='markers',
             marker=dict(size=0.5, 
                         color=counts, 
                         colorscale=pl_algae, 
                         showscale=True,
                         colorbar=dict(
                                     thickness=20,  
                                     ticklen=4
                                     )),             
           text=text, 
           hoverinfo='text'
          )    

axis = dict(showgrid=False,
           showline=True,
           zeroline=False,
           ticklen=4 
           )
layout = go.Layout(title='Hexbin plot',
                   width=530, height=550,
                   xaxis=axis,
                   yaxis=axis,
                   hovermode='closest',
                   shapes=shapes,
                   plot_bgcolor='black')

figb = go.FigureWidget(data=[trace], layout = layout)

figb.update_layout(title = labels_titles["2"] + "\n Neuron #%d" % sorted_idx[-list_neurons["2"]],
                  title_x = 0.5, 
                  xaxis_title='X-coordinate (cm)',
                  xaxis=dict(mirror=True,
                             ticks='outside',
                             showline=True,
                             linecolor='#000',
                             tickvals = [0,20,40,60,80,100], 
                             tickfont = dict(size=20)), 
                  yaxis_title='Y-coordinate (cm)',
                  yaxis=dict(mirror=True,
                             ticks='outside', 
                             showline=True,
                             linecolor='#000',
                             tickfont = dict(size=20)),
                  plot_bgcolor='#fff', 
                  width = 620, 
                  height = 600,
                  shapes=shapes,
                  hovermode='closest',
                  margin=go.layout.Margin(l=50,
                                          r=50),
                  font = dict(size = 17))

plot(figb, filename = 'fig5_b.html', config = config)
# THEBELAB
display(HTML('fig5_b.html'))
# BINDER
# iplot(figb,config=config)    

(c): Neuron #41

%use Python3
from hexplot import  get_hexbin_attributes, pl_cell_color, make_hexagon, mpl_to_plotly
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# import cmocean#  http://matplotlib.org/cmocean/
import pickle
import plotly.graph_objs as go

with open('train.pickle', 'rb') as f:
    X, y,sorted_idx = pickle.load(f, encoding='bytes')

    
list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'}     
    
x = y[...,0]
y = y[...,1]

plt.figure(figsize=(0.05,0.05))
plt.axis('off')
HB = plt.hexbin(x, y, X[...,sorted_idx[-list_neurons["3"]]], gridsize = 15, cmap='jet') # cmocean.cm.algae is a cmocean colormap
%use Python3
import plotly.graph_objects as go
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
from IPython.core.display import display, HTML
init_notebook_mode(connected = True)
config={'showLink': False, 'displayModeBar': False}

# Calculations for fig5.c
hexagon_vertices, offsets, mpl_facecolors, counts = get_hexbin_attributes(HB)
hexagon_vertices[:-1]# the last vertex coincides with the first one
cell_color = pl_cell_color(mpl_facecolors)
shapes = []
centers = []

for k in range(len(offsets)):
    shape, center = make_hexagon(hexagon_vertices, offsets[k], cell_color[k])
    shapes.append(shape)
    centers.append(center)
    

pl_algae = mpl_to_plotly(HB.cmap,11)
X, Y = zip(*centers)

#define  text to be  displayed on hovering the mouse over the cells
text = [f'x: {round(X[k],2)}<br>y: {round(Y[k],2)}<br>Counts: {int(counts[k])}' for k in range(len(X))]

trace = go.Scatter(
             x=list(X), 
             y=list(Y), 
             mode='markers',
             marker=dict(size=0.5, 
                         color=counts, 
                         colorscale=pl_algae, 
                         showscale=True,
                         colorbar=dict(
                                     thickness=20,  
                                     ticklen=4
                                     )),             
           text=text, 
           hoverinfo='text'
          )    

axis = dict(showgrid=False,
           showline=True,
           zeroline=False,
           ticklen=4 
           )
layout = go.Layout(title='Hexbin plot',
                   width=530, height=550,
                   xaxis=axis,
                   yaxis=axis,
                   hovermode='closest',
                   shapes=shapes,
                   plot_bgcolor='black')

figc = go.FigureWidget(data=[trace], layout = layout)

figc.update_layout(title = labels_titles["3"] + "\n Neuron #%d" % sorted_idx[-list_neurons["3"]],
                  title_x = 0.5, 
                  xaxis_title='X-coordinate (cm)',
                  xaxis=dict(mirror=True,
                             ticks='outside',
                             showline=True,
                             linecolor='#000',
                             tickvals = [0,20,40,60,80,100], 
                             tickfont = dict(size=20)), 
                  yaxis_title='Y-coordinate (cm)',
                  yaxis=dict(mirror=True,
                             ticks='outside', 
                             showline=True,
                             linecolor='#000',
                             tickfont = dict(size=20)),
                  plot_bgcolor='#fff', 
                  width = 620, 
                  height = 600,
                  shapes=shapes,
                  hovermode='closest',
                  margin=go.layout.Margin(l=50,
                                          r=50),
                  font = dict(size = 17))

plot(figc, filename = 'fig5_c.html', config = config)
# THEBELAB
display(HTML('fig5_c.html'))
# BINDER
# iplot(figc,config=config)    

(d) Neuron #17

%use Python3
from hexplot import  get_hexbin_attributes, pl_cell_color, make_hexagon, mpl_to_plotly
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# import cmocean#  http://matplotlib.org/cmocean/
import pickle
import plotly.graph_objs as go

with open('train.pickle', 'rb') as f:
    X, y,sorted_idx = pickle.load(f, encoding='bytes')

    
list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'}     
    
x = y[...,0]
y = y[...,1]

plt.figure(figsize=(0.05,0.05))
plt.axis('off')
HB = plt.hexbin(x, y, X[...,sorted_idx[-list_neurons["4"]]], gridsize = 15, cmap='jet') # cmocean.cm.algae is a cmocean colormap
%use Python3
import plotly.graph_objects as go
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
from IPython.core.display import display, HTML
init_notebook_mode(connected = True)
config={'showLink': False, 'displayModeBar': False}

# Calculations for fig5.d
hexagon_vertices, offsets, mpl_facecolors, counts = get_hexbin_attributes(HB)
hexagon_vertices[:-1]# the last vertex coincides with the first one
cell_color = pl_cell_color(mpl_facecolors)
shapes = []
centers = []

for k in range(len(offsets)):
    shape, center = make_hexagon(hexagon_vertices, offsets[k], cell_color[k])
    shapes.append(shape)
    centers.append(center)
    

pl_algae = mpl_to_plotly(HB.cmap,11)
X, Y = zip(*centers)

#define  text to be  displayed on hovering the mouse over the cells
text = [f'x: {round(X[k],2)}<br>y: {round(Y[k],2)}<br>Counts: {int(counts[k])}' for k in range(len(X))]

trace = go.Scatter(
             x=list(X), 
             y=list(Y), 
             mode='markers',
             marker=dict(size=0.5, 
                         color=counts, 
                         colorscale=pl_algae, 
                         showscale=True,
                         colorbar=dict(
                                     thickness=20,  
                                     ticklen=4
                                     )),             
           text=text, 
           hoverinfo='text'
          )    

axis = dict(showgrid=False,
           showline=True,
           zeroline=False,
           ticklen=4 
           )
layout = go.Layout(title='Hexbin plot',
                   width=530, height=550,
                   xaxis=axis,
                   yaxis=axis,
                   hovermode='closest',
                   shapes=shapes,
                   plot_bgcolor='black')

figd = go.FigureWidget(data=[trace], layout = layout)

figd.update_layout(title = labels_titles["4"] + "\n Neuron #%d" % sorted_idx[-list_neurons["4"]],
                  title_x = 0.5, 
                  xaxis_title='X-coordinate (cm)',
                  xaxis=dict(mirror=True,
                             ticks='outside',
                             showline=True,
                             linecolor='#000',
                             tickvals = [0,20,40,60,80,100], 
                             tickfont = dict(size=20)), 
                  yaxis_title='Y-coordinate (cm)',
                  yaxis=dict(mirror=True,
                             ticks='outside', 
                             showline=True,
                             linecolor='#000',
                             tickfont = dict(size=20)),
                  plot_bgcolor='#fff', 
                  width = 620, 
                  height = 600,
                  shapes=shapes,
                  hovermode='closest',
                  margin=go.layout.Margin(l=50,
                                          r=50),
                  font = dict(size = 17))

plot(figd, filename = 'fig5_d.html', config = config)
# THEBELAB
display(HTML('fig5_d.html'))
# BINDER
# iplot(figd,config=config)    

(e): Neuron #

%use Python3
from hexplot import  get_hexbin_attributes, pl_cell_color, make_hexagon, mpl_to_plotly
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# import cmocean#  http://matplotlib.org/cmocean/
import pickle
import plotly.graph_objs as go

with open('train.pickle', 'rb') as f:
    X, y,sorted_idx = pickle.load(f, encoding='bytes')

    
list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'}     
    
x = y[...,0]
y = y[...,1]

plt.figure(figsize=(0.05,0.05))
plt.axis('off')
HB = plt.hexbin(x, y, X[...,sorted_idx[-list_neurons["5"]]], gridsize = 15, cmap='jet') # cmocean.cm.algae is a cmocean colormap
%use Python3
import plotly.graph_objects as go
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
from IPython.core.display import display, HTML
init_notebook_mode(connected = True)
config={'showLink': False, 'displayModeBar': False}

# Calculations for fig5.e
hexagon_vertices, offsets, mpl_facecolors, counts = get_hexbin_attributes(HB)
hexagon_vertices[:-1]# the last vertex coincides with the first one
cell_color = pl_cell_color(mpl_facecolors)
shapes = []
centers = []

for k in range(len(offsets)):
    shape, center = make_hexagon(hexagon_vertices, offsets[k], cell_color[k])
    shapes.append(shape)
    centers.append(center)
    

pl_algae = mpl_to_plotly(HB.cmap,11)
X, Y = zip(*centers)

#define  text to be  displayed on hovering the mouse over the cells
text = [f'x: {round(X[k],2)}<br>y: {round(Y[k],2)}<br>Counts: {int(counts[k])}' for k in range(len(X))]

trace = go.Scatter(
             x=list(X), 
             y=list(Y), 
             mode='markers',
             marker=dict(size=0.5, 
                         color=counts, 
                         colorscale=pl_algae, 
                         showscale=True,
                         colorbar=dict(
                                     thickness=20,  
                                     ticklen=4
                                     )),             
           text=text, 
           hoverinfo='text'
          )    

axis = dict(showgrid=False,
           showline=True,
           zeroline=False,
           ticklen=4 
           )
layout = go.Layout(title='Hexbin plot',
                   width=530, height=550,
                   xaxis=axis,
                   yaxis=axis,
                   hovermode='closest',
                   shapes=shapes,
                   plot_bgcolor='black')

fige = go.FigureWidget(data=[trace], layout = layout)

fige.update_layout(title = labels_titles["5"] + "\n Neuron #%d" % sorted_idx[-list_neurons["5"]],
                  title_x = 0.5, 
                  xaxis_title='X-coordinate (cm)',
                  xaxis=dict(mirror=True,
                             ticks='outside',
                             showline=True,
                             linecolor='#000',
                             tickvals = [0,20,40,60,80,100], 
                             tickfont = dict(size=20)), 
                  yaxis_title='Y-coordinate (cm)',
                  yaxis=dict(mirror=True,
                             ticks='outside', 
                             showline=True,
                             linecolor='#000',
                             tickfont = dict(size=20)),
                  plot_bgcolor='#fff', 
                  width = 620, 
                  height = 600,
                  shapes=shapes,
                  hovermode='closest',
                  margin=go.layout.Margin(l=50,
                                          r=50),
                  font = dict(size = 17))

plot(fige, filename = 'fig5_e.html', config = config)
# THEBELAB
display(HTML('fig5_e.html'))
# BINDER
# iplot(fige,config=config)    

(f): Neuron #9

%use Python3
from hexplot import  get_hexbin_attributes, pl_cell_color, make_hexagon, mpl_to_plotly
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
# import cmocean#  http://matplotlib.org/cmocean/
import pickle
import plotly.graph_objs as go

with open('train.pickle', 'rb') as f:
    X, y,sorted_idx = pickle.load(f, encoding='bytes')

    
list_neurons = {"1":53, 
                "2":14, 
                "3":2, 
                "4":1, 
                "5":18, 
                "6":48}

labels_titles = {"1": '(a)',
                 "2": '(b)', 
                 "3": '(c)',
                 "4": '(d)',
                 "5": '(e)',
                 "6": '(f)'}     
    
x = y[...,0]
y = y[...,1]

plt.figure(figsize=(0.05,0.05))
plt.axis('off')
HB = plt.hexbin(x, y, X[...,sorted_idx[-list_neurons["6"]]], gridsize = 15, cmap='jet') # cmocean.cm.algae is a cmocean colormap
%use Python3
import plotly.graph_objects as go
import plotly.tools as tls
from plotly.offline import plot, iplot, init_notebook_mode
from IPython.core.display import display, HTML
init_notebook_mode(connected = True)
config={'showLink': False, 'displayModeBar': False}

# Calculations for fig5.f
hexagon_vertices, offsets, mpl_facecolors, counts = get_hexbin_attributes(HB)
hexagon_vertices[:-1]# the last vertex coincides with the first one
cell_color = pl_cell_color(mpl_facecolors)
shapes = []
centers = []

for k in range(len(offsets)):
    shape, center = make_hexagon(hexagon_vertices, offsets[k], cell_color[k])
    shapes.append(shape)
    centers.append(center)
    

pl_algae = mpl_to_plotly(HB.cmap,11)
X, Y = zip(*centers)

#define  text to be  displayed on hovering the mouse over the cells
text = [f'x: {round(X[k],2)}<br>y: {round(Y[k],2)}<br>Counts: {int(counts[k])}' for k in range(len(X))]

trace = go.Scatter(
             x=list(X), 
             y=list(Y), 
             mode='markers',
             marker=dict(size=0.5, 
                         color=counts, 
                         colorscale=pl_algae, 
                         showscale=True,
                         colorbar=dict(
                                     thickness=20,  
                                     ticklen=4
                                     )),             
           text=text, 
           hoverinfo='text'
          )    

axis = dict(showgrid=False,
           showline=True,
           zeroline=False,
           ticklen=4 
           )
layout = go.Layout(title='Hexbin plot',
                   width=530, height=550,
                   xaxis=axis,
                   yaxis=axis,
                   hovermode='closest',
                   shapes=shapes,
                   plot_bgcolor='black')

figf = go.FigureWidget(data=[trace], layout = layout)

figf.update_layout(title = labels_titles["6"] + "\n Neuron #%d" % sorted_idx[-list_neurons["6"]],
                  title_x = 0.5, 
                  xaxis_title='X-coordinate (cm)',
                  xaxis=dict(mirror=True,
                             ticks='outside',
                             showline=True,
                             linecolor='#000',
                             tickvals = [0,20,40,60,80,100], 
                             tickfont = dict(size=20)), 
                  yaxis_title='Y-coordinate (cm)',
                  yaxis=dict(mirror=True,
                             ticks='outside', 
                             showline=True,
                             linecolor='#000',
                             tickfont = dict(size=20)),
                  plot_bgcolor='#fff', 
                  width = 620, 
                  height = 600,
                  shapes=shapes,
                  hovermode='closest',
                  margin=go.layout.Margin(l=50,
                                          r=50),
                  font = dict(size = 17))

plot(figf, filename = 'fig5_f.html', config = config)
# THEBELAB
display(HTML('fig5_f.html'))
# BINDER
# iplot(figf,config=config)